<?php
declare (strict_types = 1);

namespace app\controller;

use app\model\Enterprise as TeamModel;
use app\BaseController;
use app\model\TeamInvite;
use app\model\EnterpriseMember;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Request;
use think\Response;
use think\response\Json;

class Enterprise  extends BaseController
{
    //团队模型
    protected TeamModel $model;
    // 团队创建限制，从.env配置文件中读取
    protected int $limit;
    protected array $fields  = ['id', 'name', 'user_id', 'avatar','status'];
    public function initialize(): void
    {
        $this->limit = env('ENTERPRISE_CREATE_LIMIT') | 5;
        $this->model = new TeamModel();
    }

    /**
     * 显示资源列表
     *
     * @return Response
     */
    public function index(): Response
    {
        $userId = $this->request->get('user_id',0,'int');
        if(!$userId){
            return $this->result(400, '无法获取用户ID，请重新登录');
        }
        $data = $this->model->getEnterpriseListByUserId($userId);
        return $this->result(200, '获取成功', [
            'data'=>$data,
            'limit'=>$this->limit
        ]);
    }

    /**
     * 根据名称搜索团队名称
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function search(Request $request): Json
    {
        $name = $request->get('name','');
        if(!$name){
            return $this->result(403,'团队名称不能为空');
        }
        $result = $this->model->where('name','like','%'.$name.'%')
            ->field($this->fields)->limit(10)->select();
        return $this->result(200,'获取成功',$result);
    }
    /**
     *  创建团队
     *
     * @param Request $request
     * @return Response
     */
    public function save(Request $request): Response
    {
        $data = $request->post();
        //检查团队名称是否重复
        try {
            $team = $this->model->where('name', $data['name'])
                ->where('user_id', $data['user_id'])
                ->find();
            if ($team) {
                return apiResponse(400, '团队名称重复');
            }
            //检测团队成员是否超过限制
            $count = $this->model->where('user_id', $data['user_id'])->count();
            if ($count >= $this->limit) {
                return apiResponse(400, '个人允许创建团队数量为'.$this->limit);
            }
            $this->model->save($data);
            $data['id'] = $this->model->getKey();
            return apiResponse(200, '创建成功',$data);
        } catch (DataNotFoundException|DbException|Exception $e) {
           return apiResponse($e->getCode(),$e->getMessage());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param Request $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return Response
     */
    public function delete($id)
    {
        //
    }

    /**
     * 处理团队加入邀请请求
     * 本函数旨在处理用户申请加入特定团队的逻辑，包括检查用户是否为团队创建者、是否已加入团队，
     * 以及是否已发送过加入申请，以确保每个用户只能发送一次申请
     *
     * @param Request $request 用户请求数据，包含team_id和user_id
     * @return Json 返回处理结果的JSON响应，包括状态码和消息
     */
    public function invite(Request $request): Json
    {
        $data = $request->post();
        //检测团队是否由用户创建，检测用户是否已经加入团队
        try {
            $team = $this->model->where('id', $data['team_id'])
                ->where('user_id', $data['user_id'])
                ->find();
            if ($team) {
                return $this->result(400, '您已经是团队创建者，无需申请加入团队');
            }
            //检测是否已经加入团队
            $member = (new EnterpriseMember())->where('team_id', $data['team_id'])
                ->where('user_id', $data['user_id'])
                ->find();
            if($member){
                return $this->result(400, '您已经加入团队，无需重复申请');
            }
            $teamInvite = new TeamInvite();
            $isInvite = $teamInvite->where('team_id', $data['team_id'])
                ->where('user_id', $data['user_id'])->find();
            if($isInvite){
                return $this->result(400, '您已经申请加入团队，无需重复申请');
            }
            $teamInvite->save($data);
            return $this->result(200, '申请成功,请等待管理员审核');
        }catch (DataNotFoundException|ModelNotFoundException|DbException $e){
            return $this->result($e->getCode(),$e->getMessage());
        }
    }
}
